package com.slt.developkitweb.crm;

import org.springframework.cglib.beans.BeanMap;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

public class Signer {

    public static String sign(String signContent,String key) throws Exception {
        return  GmwSm2Utils.sign(signContent, key);
    }

    public static Boolean verify(String hmac,String signContent,String key) throws Exception {
        return  GmwSm2Utils.verify(hmac,signContent, key);
    }

    //生成用来签名的内容
    public static   <T> String toSignContent(T bean, Set<String> ignoreKey){
        //转Map
        Map<String, Object> beanMap = bean2Map(bean);
        return toSignContent(beanMap,ignoreKey);

    }


    //生成用来签名的内容
    public static   <T> String toSignContent(Map<String, Object> beanMap, Set<String> ignoreKey){
        //转Map

        //key按字母排序
        List<String> keyListSort = new ArrayList<>(beanMap.keySet()).stream().sorted().collect(Collectors.toList());
        List<String> keyAndVal = new ArrayList<>();
        keyListSort.forEach(key-> {
            Object valObj = beanMap.get(key);
            if (valObj!=null){
                if (!(!CollectionUtils.isEmpty(ignoreKey)&&ignoreKey.contains(key)) && !"hmac".equals(key)){
                    String valStr;
                    if (valObj instanceof String ||valObj instanceof Integer || valObj instanceof BigDecimal) {
                        valStr = String.valueOf(valObj);
                    } else if (valObj instanceof List) {
                        valStr = CrmPaasConstant.gson.toJson(valObj);
                    } else {
                        valStr = CrmPaasConstant.gson.toJson(valObj);
                    }
                    keyAndVal.add(key+"="+valStr);
                }
            }
        });
        return String.join("&", keyAndVal);

    }


    //bean转成Map
    public static  <T> Map<String, Object> bean2Map(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }
}
